//配置axios的全局基本路径(每次发axios请求都会用这个路径)
axios.defaults.baseURL='http://localhost:8080'
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
//在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios
//屏蔽vue的警告
Vue.config.productionTip = false

//======================axios的前置拦截器【拦截调用后端的请求====================//
axios.interceptors.request.use(res=>{
    //alert("前置拦截器")
    let token = localStorage.getItem("token");
    if(token){
        res.headers["token"] = token;
    }
    return res;
},error => {
    Promise.reject(error)
})
//======================axios的前置拦截器【拦截调用后端的请求】====================//

//======================axios的后置拦截器【处理后台登录拦截的结果】====================//
axios.interceptors.response.use(res => {
    //alert("后置拦截器")
    //后端响应的是没有登录的信息
    if (false === res.data.success && "noLogin" === res.data.message) {
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        location.href="/login.html";
    }else if (false === res.data.success && "timeOut" === res.data.message){
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        alert("登录状态已过期，请重新登录")
        location.href="/login.html";
    }
    return res;
},error => {
    Promise.reject(error)
})
//======================axios的后置拦截器【处理后台登录拦截的结果】====================//

//静态资源拦截器，拦截不发axios请求的页面
//前端的登录拦截-common.js会被所有的界面导入
// 判断localStorage中是否有logininfo
var url = location.href;
//不是登录且不是注册，就要拦截
if(url.indexOf("login.html")==-1 && url.indexOf("register.html")==-1
    && url.indexOf("binder.html")==-1 && url.indexOf("callback.html")==-1){
    let loginInfo = localStorage.getItem("logininfo");
    if(!loginInfo){
        location.href = "/login.html"
    }
}

//封装公用方法 - 将字符串的参数解析为json对象
function parseUrlParams2Obj(url) {//xxx?code=xxx&state=1
    let paramStr = url.substring(url.indexOf("?")+1);//code=xxx&state=1
    let paramArr = paramStr.split("&");//[code=xxx,state=1]
    let paramObj = {};
    for(let i = 0;i<paramArr.length;i++){
        let paramTemp = paramArr[i];//code=xxx
        let paramName = paramTemp.split("=")[0];//code
        let paramValue= paramTemp.split("=")[1];//xxx
        paramObj[paramName] = paramValue;//{code:xxx,state:1}
    }
    return paramObj;
}